<template>
<div class="app-container">
    <!-- 课程信息表单 -->
    <el-form label-width="120px" :rules="rules" ref="courseInfoForm" :model="courseInfo">
        <el-form-item label="课程标题" prop="title">
            <el-input v-model="courseInfo.title" placeholder=" 示例：机器学习项目课：从基础到搭建项目视频课程。专业名称注意大小写" />
        </el-form-item>

        <!-- 课程讲师 -->
        <el-form-item label="课程讲师" prop="teacherId">
            <el-select v-model="courseInfo.teacherId" placeholder="请选择">
                <el-option v-for="teacher in teacherList" :key="teacher.id" :value="teacher.id" :label="teacher.name" />
            </el-select>
        </el-form-item>

        <!-- 所属分类 -->
        <el-form-item label="课程分类">
            <!-- 一级分类 -->
            <el-select v-model="courseInfo.subjectParentId" placeholder="请选择" @change="subjectChanged" porp="subjectParentId">
                <el-option v-for="subject in subjectList" :key="subject.id" :value="subject.id" :label="subject.title" />
            </el-select>
            <!-- 二级分类 -->
            <el-select v-model="courseInfo.subjectId" placeholder="请选择" prop="subjectId">
                <el-option v-for="subject in subjectLevelTwoList" :key="subject.id" :value="subject.id" :label="subject.title" />
            </el-select>
        </el-form-item>

        <el-form-item label="总课时" prop="lessonNum">
            <el-input-number :min="0" v-model="courseInfo.lessonNum" controls-position="right" placeholder="请填写课程的总课时数" />
        </el-form-item>

        <!-- 课程简介-->
        <el-form-item label="课程简介" prop="description">
            <tinymce :height="300" v-model="courseInfo.description" />
        </el-form-item>

        <!-- 课程封面 -->
        <el-form-item label="课程封面">
            <el-upload :show-file-list="false" :on-success="handleCoverSuccess" :before-upload="beforeCoverUpload" :on-error="handleCoverError" class="cover-uploader" :action="BASE_API + '/admin/oss/file/upload?module=cover'">
                <img v-if="courseInfo.cover" :src="courseInfo.cover" />
                <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
        </el-form-item>

        <el-form-item label="课程价格" prop="price">
            <el-input-number :min="0" v-model="courseInfo.price" controls-position="right" placeholder="免费课程请设置为0元" />
            元
        </el-form-item>

        <el-row>
            <el-col :span="2" :offset="11">
                <el-form-item>
                    <el-button type="primary" plain :disabled="btnDisabled" @click="nextAndSave()">保存并下一步</el-button>
                </el-form-item>
            </el-col>
        </el-row>
    </el-form>
</div>
</template>

<script>
import courseInfoApi from "@/api/course";
import teacherApi from "@/api/teacher";
import subjectApi from "@/api/subject";
import Tinymce from "@/components/Tinymce";

export default {
    name: "",
    props: {},
    components: {
        Tinymce,
    },
    data() {
        return {
            btnDisabled: false,
            courseInfo: {
                // price: 0,
                // lessonNum: 0,
                // // 以下解决表单数据不全时insert语句非空校验
                // teacherId: '',
                subjectId: "",
                // subjectParentId: '',
                // cover: '',
                // description: ''
            },
            BASE_API: process.env.BASE_API,
            teacherList: [],
            subjectList: [],
            subjectLevelTwoList: [],
            rules: {
                title: [{
                    required: true,
                    message: "请输入课程标题",
                    trigger: "blur",
                }, ],
                teacherId: [{
                    required: true,
                    message: "请选择课程讲师",
                    trigger: "change",
                }, ],
                subjectParentId: [{
                    required: true,
                    message: "请选择课程一级分类",
                    trigger: "change",
                }, ],
                subjectId: [{
                    required: true,
                    message: "请选择课程二级分类",
                    trigger: "change",
                }, ],
                lessonNum: [{
                    type: "number",
                    required: true,
                    message: "请输入总课时",
                    trigger: "blur",
                }, ],
                description: [{
                    required: true,
                    message: "请输入课程简介",
                    trigger: "blur",
                }, ],
                price: [{
                    type: "number",
                    required: true,
                    message: "请输入课程价格",
                    trigger: "blur",
                }, ],
            },
        };
    },
    computed: {},
    watch: {},
    methods: {
        //初始化讲师数据
        initTeacherList() {
            teacherApi.list().then((req) => {
                if (req.code == 20000) {
                    this.teacherList = req.data.data;
                } else {
                    this.$message("获取讲师列表失败：" + req.message);
                }
            });
        },
        //初始化课程分类数据
        initSubjectList() {
            subjectApi.getSubjectTreeList().then((req) => {
                if (req.code == 20000) {
                    this.subjectList = req.data.items;
                } else {
                    this.$message("获取课程分类列表失败：" + req.message);
                }
            });
        },
        //课程一级分类改变触发
        subjectChanged(val) {
            if (val != "") {
                //遍历一级类别
                this.subjectList.forEach((subject) => {
                    if (subject.id == val) {
                        this.courseInfo.subjectId = "";
                        this.subjectLevelTwoList = subject.children;
                    }
                });
            }
        },
        //下一步
        nextAndSave() {
            this.$refs.courseInfoForm.validate((valid) => {
                if (valid) {
                    this.btnDisabled = true;
                    if (this.$parent.courseId != null) {
                        this.upData();
                    } else {
                        this.saveData();
                    }
                } else {
                    this.$message.error("请填写完整！");
                    return false;
                }
            });
        },
        //保存课程数据
        saveData() {
            courseInfoApi.saveCourseInfo(this.courseInfo).then((req) => {
                if (req.code == 20000) {
                    this.$message({
                        message: req.message,
                        type: "success",
                    });
                    this.$parent.active = 1;
                    this.$parent.courseId = req.data.courseId;
                } else {
                    this.$message(req.message);
                }
            });
        },
        //更新课程数据
        upData() {
            courseInfoApi.updateCourseInfoById(this.courseInfo).then((req) => {
                if (req.code == 20000) {
                    this.$message({
                        message: req.message,
                        type: "success",
                    });
                    this.$parent.active = 1;
                } else {
                    this.$message(req.message);
                }
            });
        },
        //上传图片封面之前触发
        beforeCoverUpload(file) {
            //是否为JPG,PNG图片
            const isJSP = file.type === "image/jpeg";
            const isPNG = file.type === "image/png";
            //是否小于2M
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJSP && !isPNG) {
                this.$message.error("上传封面图片只能是JPG或者PNG格式！");
            }
            if (!isLt2M) {
                this.$message.error("上传封面图片的大小不能超过2MB！");
            }
            return isPNG || (isJSP && isLt2M);
        },
        //上传图片封面成功触发
        handleCoverSuccess(req, file, fileList) {
            if (req.code == 20000) {
                this.$message({
                    message: "封面图片上传成功！",
                    type: "success",
                });
                this.courseInfo.cover = req.data.url;
                //强制重新渲染
                this.$forceUpdate();
            } else {
                this.$message.error("封面图片上传失败！");
            }
        },
        //上传图片封面错误触发
        handleCoverError() {},
        //根据id回填课程基本信息
        getCourseInfoById(id) {
            courseInfoApi.getCourseInfoById(id).then((req) => {
                this.courseInfo = req.data.item;

                //课程类别渲染
                subjectApi.getSubjectTreeList().then((subject) => {
                    if (subject.code == 20000) {
                        this.subjectList = subject.data.items;
                        this.subjectList.forEach((element) => {
                            if (element.id === this.courseInfo.subjectParentId) {
                                this.subjectLevelTwoList = element.children;
                            }
                        });
                    } else {
                        this.$message.error("获取课程分类列表失败：" + subject.message);
                    }
                });
            });
        },
    },
    created() {
        //如果是点击编辑进入页面时
        // if (this.$route.name === "CourseInfoEdit") {
        //     this.$parent.courseId = this.$route.params.id
        // }

        //如果父id不为空，回填基础基本信息
        if (this.$parent.courseId) {
            this.getCourseInfoById(this.$parent.courseId);
        } else {
            this.initSubjectList();
        }

        this.initTeacherList();
    },
    mounted() {},
    beforeDestroy() {},
};
</script>

<style>
.tinymce-container {
    position: relative;
    line-height: normal;
}

.cover-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.cover-uploader .el-upload:hover {
    border-color: #409eff;
}

.cover-uploader .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 640px;
    height: 357px;
    line-height: 357px;
    text-align: center;
}

.cover-uploader img {
    width: 640px;
    height: 357px;
    display: block;
}
</style>
